package com.example.jf.jfapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.jf.jfapp.adapter.BlogCommentAdapter;
import com.example.jf.jfapp.bean.request.BlogCollectRequest;
import com.example.jf.jfapp.bean.request.BlogCommentRequest;
import com.example.jf.jfapp.bean.response.BlogCommentResponse;
import com.example.jf.jfapp.bean.response.BlogResponse;
import com.example.jf.jfapp.utils.AppConfigUtils;
import com.example.jf.jfapp.utils.Constant;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.example.jf.jfapp.BlogCommentActivity.REAMBEAN;
import static com.example.jf.jfapp.BlogCommentEditActivity.STATU_ID_KEY;
import static com.example.jf.jfapp.utils.OkHttpUtils.getOkHttpClient;
import static com.example.jf.jfapp.utils.RequestUtils.requestPOST;

public class BlogDetailActivity extends AppCompatActivity {
    public static final String BEAN = "Bean";
    private static final String TAG ="BlogDetailActivity" ;
    @BindView(R.id.back_blog)
    ImageView backBlog;
    @BindView(R.id.blogcomment)
    ImageView blogcomment;
    @BindView(R.id.author_picture)
    ImageView authorPicture;
    @BindView(R.id.author_name)
    TextView authorName;
    @BindView(R.id.author_sign)
    TextView authorSign;
    @BindView(R.id.blogglance)
    ImageView blogglance;
    @BindView(R.id.blogglancesizes)
    TextView blogglancesizes;
    @BindView(R.id.blognews)
    ImageView blognews;
    @BindView(R.id.blogcommentsizes)
    TextView blogcommentsizes;
    @BindView(R.id.collectarticle)
    Button collectarticle;
    @BindView(R.id.writecomment)
    TextView writecomment;
    @BindView(R.id.contentArr1)
    TextView contentArr1;
    @BindView(R.id.contentimageArr1)
    ImageView contentimageArr1;
    @BindView(R.id.contentArr2)
    TextView contentArr2;
    @BindView(R.id.contentimageArr2)
    ImageView contentimageArr2;
    @BindView(R.id.contentArr3)
    TextView contentArr3;
    @BindView(R.id.contentimageArr3)
    ImageView contentimageArr3;
    @BindView(R.id.blogtalkcomment)
    RecyclerView blogtalkcomment;
    @BindView(R.id.blogtitle)
    TextView blogtitle;
    @BindView(R.id.lookmore)
    Button lookmore;

    @BindView(R.id.scrollView)
    ScrollView scrollView;

    private BlogResponse.ResultBean mResultBean;

    private BlogCommentRequest mBlogCommentRequest;

    ArrayList<BlogCommentResponse.ResultBean> mComResultBean=new ArrayList<>();

    private BlogCommentAdapter mBlogCommentAdapter;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blog_detail);
        ButterKnife.bind(this);
        mResultBean = getIntent().getParcelableExtra(BEAN);
        Glide.with(this)
                .load(mResultBean.getAuthor().getHeadProtrait())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(authorPicture);
        authorName.setText(mResultBean.getAuthor().getUsername()+"");
        blogtitle.setText(mResultBean.getTitle()+"");

        blogglancesizes.setText(mResultBean.getLikeSize()+"");
        blogcommentsizes.setText(mResultBean.getCommentsSize()+"");

        List<String> images=new ArrayList<>();
        List<String> texts=new ArrayList<>();

        for (int i = 0; i <mResultBean.getContentArr().size(); i++) {
            String content=mResultBean.getContentArr().get(i);
            if(content!=null&&!content.isEmpty()){
                if (content.contains("http://")){
                    images.add(content);
                }else {
                    texts.add(content);
                }
            }
        }
        if(images.size()>0){
            Glide.with(this)
                    .load(images.get(0))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(contentimageArr1);
        }
        if(images.size()>1){
            Glide.with(this)
                    .load(images.get(1))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(contentimageArr2);
        }
        if(images.size()>2){
            Glide.with(this)
                    .load(images.get(2))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(contentimageArr3);
        }
       if(texts.size()>0){
           contentArr1.setText(texts.get(0));
       }
        if(texts.size()>1){
            contentArr2.setText(texts.get(1));
        }
        if(texts.size()>2){
            contentArr3.setText(texts.get(2));
        }




        blogtalkcomment.setLayoutManager(new LinearLayoutManager(this));
        mBlogCommentAdapter=new BlogCommentAdapter(this,mComResultBean);
        blogtalkcomment.setAdapter(mBlogCommentAdapter);
        mBlogCommentRequest=new BlogCommentRequest(mResultBean.getBlogId(),10,0);


        getCommentData();


//        String content1=mResultBean.getContentArr().get(0);
//        if(content1!=null||!content1.isEmpty()){
//            if(content1.contains("http:")){//如果第一个包含图片，contentimageArr1加载
//                Glide.with(this)
//                        .load(content1)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .into(contentimageArr1);
//            }else {//（第一个不是图片）否则第一个textview显示它，再判断第二个是否是图片
//                contentArr1.setText(content1);
//            }
//        }
//        String content2=mResultBean.getContentArr().get(1);
//        if(content2!=null||!content2.isEmpty()){
//            if(content2.contains("http:")){//如果第一个包含图片，contentimageArr1加载
//                Glide.with(this)
//                        .load(content1)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .into(contentimageArr2);
//            }else {//（第一个不是图片）否则第一个textview显示它，再判断第二个是否是图片
//                contentArr2.setText(content1);
//            }
//        }
//        String content3=mResultBean.getContentArr().get(2);
//        if(content3!=null||!content3.isEmpty()){
//            if(content3.contains("http:")){//如果第一个包含图片，contentimageArr1加载
//                Glide.with(this)
//                        .load(content1)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .into(contentimageArr3);
//            }else {//（第一个不是图片）否则第一个textview显示它，再判断第二个是否是图片
//                contentArr3.setText(content1);
//            }
//        }

//        if(content1.contains("http:")){//如果第一个包含图片，contentimageArr1加载
//            Glide.with(this)
//                    .load(content1)
//                    .diskCacheStrategy(DiskCacheStrategy.ALL)
//                    .into(contentimageArr1);
//        }else {//（第一个不是图片）否则第一个textview显示它，再判断第二个是否是图片
//            contentArr1.setText(content1);
//            String content2=mResultBean.getContentArr().get(1);
//            if(content2.contains("http:")){//第二个是图片的话，contentimageArr1加载它
//                Glide.with(this)
//                        .load(content2)
//                        .diskCacheStrategy(DiskCacheStrategy.ALL)
//                        .into(contentimageArr1);
//            }else {//链表第二个数据也不是图片的话，第一个textview contentArr2设置值
//                contentArr2.setText(content2);
//                String content3=mResultBean.getContentArr().get(2);
//
//                if(content3.contains("http:")){//第三个是图片的话，contentimageArr2加载它
//                    Glide.with(this)
//                            .load(content3)
//                            .diskCacheStrategy(DiskCacheStrategy.ALL)
//                            .into(contentimageArr2);
//                }else {//链表第三个数据也不是图片的话，第三个textview contentArr3设置值
//                    contentArr3.setText(content3);
//                    Glide.with(this)
//                            .load(mResultBean.getContentArr().get(3))
//                            .diskCacheStrategy(DiskCacheStrategy.ALL)
//                            .into(contentimageArr3);
//                }
//            }
//        }

    }

    private void getCommentData() {
        final Request request = requestPOST(mBlogCommentRequest, Constant.URL.BLOG_COMMENT);
        OkHttpClient okHttpClient = getOkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "博客评论失败 ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                Log.e(TAG, "博客评论: "+result);
                if (result != null) {
                    BlogCommentResponse blogCommentResponse=new Gson().fromJson(result,BlogCommentResponse.class);
                    mComResultBean.addAll(blogCommentResponse.getResult());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBlogCommentAdapter.notifyDataSetChanged();
                        }
                    });
                }

            }
        });
    }

    @OnClick({R.id.back_blog, R.id.blogcomment, R.id.collectarticle, R.id.writecomment,R.id.lookmore})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_blog:
                finish();
                break;
            case R.id.blogcomment:
                int top=blogtalkcomment.getTop();
                scrollView.scrollTo(0,top);
                break;
            case R.id.collectarticle:
                if(addcoll==false){
                    collectarticle.setText("已收藏");
                }
                if(addcoll==true){
                    collectarticle.setText("收藏");
                }
                getCollectBlog();

                break;
            case R.id.writecomment:
                Intent intentcom=new Intent(this,BlogCommentEditActivity.class);
                intentcom.putExtra(STATU_ID_KEY,mResultBean.getBlogId());

                startActivityForResult(intentcom,1);


                break;
            case R.id.lookmore:
                Intent intent=new Intent(this,BlogCommentActivity.class);
                intent.putExtra(REAMBEAN,mResultBean);
                startActivity(intent);
                break;
        }

    }
    boolean addcoll=false;
    private void getCollectBlog() {
        BlogCollectRequest blogCollectRequest=new BlogCollectRequest();

        String userId= AppConfigUtils.getInstance().getLoginInfo(this).getObjectId();
        if (userId == "" || userId.isEmpty() || userId == null) {
            Toast.makeText(this, "请先登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        blogCollectRequest.setArticleType(mResultBean.getBlogType());
        blogCollectRequest.setArticleId(mResultBean.getBlogId());
        blogCollectRequest.setUserId(userId);

        final Request request = requestPOST(blogCollectRequest, Constant.URL.COLLBLOG);
        OkHttpClient okHttpClient = getOkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result=response.body().string();
                Log.e(TAG, "收藏博客: "+result);
                if(response.code()==200){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(addcoll==false){

                                Toast.makeText(BlogDetailActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                addcoll=true;
                                return;
                            }
                            if(addcoll==true){

                                Toast.makeText(BlogDetailActivity.this, "取消收藏成功", Toast.LENGTH_SHORT).show();
                                addcoll=false;
                                return;
                            }
                        }
                    });

                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode==0){
            //要把现有的清除掉，重新加载
            mComResultBean.clear();
            getCommentData();
            mBlogCommentAdapter.notifyDataSetChanged();

        }
    }
}
